package com.hawthorn.admin.service.showUserApply.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hawthorn.admin.constant.DicConstants;
import com.hawthorn.admin.feign.CloudStoreFeignService;
import com.hawthorn.admin.feign.redisService.RedisCompanyFeignService;
import com.hawthorn.admin.feign.redisService.RedisDeptFeignService;
import com.hawthorn.admin.model.po.*;
import com.hawthorn.admin.repository.*;
import com.hawthorn.admin.service.showUserApply.ShowUserApplyService;
import com.hawthorn.component.constant.DicConstant;
import com.hawthorn.component.constant.FormatConstant;
import com.hawthorn.component.utils.bean.Map2ObjUtil;
import com.hawthorn.platform.context.ContextHolder;
import com.hawthorn.platform.exception.BizCode;
import com.hawthorn.platform.service.TransResultService;
import com.hawthorn.platform.utils.iassert.AssertMyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version v1.0.1
 * @Copyright: Copyright (c) $
 * @remark: TODO 演示账号维护Impl层
 * @author:zhangzhexu
 * @date:2023/3/21$ 13:21$
 */
@Service
public class ShowUserApplyServiceImpl implements ShowUserApplyService
{
  @Resource
  private ShowUserApplyMapper showUserApplyMapper;
  @Resource
  private ShowUserApplyLogMapper showUserApplyLogMapper;
  @Resource
  private AppUserMapper appUserMapper;
  @Resource
  private SysCompanyMapper companyMapper;
  @Resource
  private SysDeptMapper deptMapper;
  @Resource
  private RedisCompanyFeignService redisCompanyFeignService;
  @Resource
  private RedisDeptFeignService redisDeptFeignService;
  @Resource
  private TransResultService transResultService;
  @Autowired
  private CloudStoreFeignService cloudStoreFeignService;

  /**
   * @remark:演示账号维护主页面查询方法
   * @param: page
   * @param: conditions
   * @return: com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
   * @author: zhangzx
   * @date: 2023/3/21 21:07
   * @version: 1.0.1
   * Modification History:
   * Date       Author       Version          Description
   * -----------------------------------------------------------
   * 2023/3/21  zhangzx       v1.0.1          init
   */
  @Override
  public IPage<Map<String, Object>> findShowUserApply(Page<Map<String, Object>> page, String conditions)
  {
    OrderItem oi = new OrderItem();
    oi.setColumn("create_time");
    oi.setAsc(false);
    List<OrderItem> al = page.getOrders();
    al.add(oi);
    page.setOrders(al);
    return transResultService.transResult(showUserApplyMapper.findShowUserApply(page, conditions), this.getTransDic());
  }

  /**
   * @remark:启用/停用演示账号方法
   * @param: id
   * @param: param
   * @return: java.lang.Integer
   * @author: zhangzx
   * @date: 2023/3/21 21:07
   * @version: 1.0.1
   * Modification History:
   * Date       Author       Version          Description
   * -----------------------------------------------------------
   * 2023/3/21  zhangzx       v1.0.1          init
   */
  @Override
  public Integer updateShowUserStatus(Long id, Map<String, Object> param)
  {
    ShowUserApplyPO showUserApplyPO = showUserApplyMapper.selectById(id);
    int applyStatus = Integer.parseInt(param.get("applyStatus").toString());
    int status = Integer.parseInt(param.get("status").toString());
    showUserApplyPO.setApplyStatus(applyStatus);
    showUserApplyPO.setStatus(status);
    showUserApplyMapper.updateById(showUserApplyPO);

    // 插入更新日志
    if (applyStatus == Integer.parseInt(DicConstants.YSZHZT_03))
    {
      this.insertShowUserApplyLog(showUserApplyPO, "停用");
    } else
    {
      this.insertShowUserApplyLog(showUserApplyPO, "启用");
    }
    return applyStatus;
  }

  /**
   * @remark:查询修改日志方法
   * @param: page
   * @param: conditions
   * @return: com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
   * @author: zhangzx
   * @date: 2023/3/21 21:08
   * @version: 1.0.1
   * Modification History:
   * Date       Author       Version          Description
   * -----------------------------------------------------------
   * 2023/3/21  zhangzx       v1.0.1          init
   */
  @Override
  public IPage<Map<String, Object>> findShowUserApplyLog(Page<Map<String, Object>> page, String conditions)
  {
    // 设置排序
    OrderItem oi = new OrderItem();
    oi.setColumn("create_time");
    oi.setAsc(false);
    List<OrderItem> al = page.getOrders();
    al.add(oi);
    page.setOrders(al);
    return transResultService.transResult(showUserApplyLogMapper.findShowUserApplyLog(page, conditions), this.getTransDic());
  }

  /**
   * @remark:保存演示账号信息
   * @param: param
   * @return: java.util.Map<java.lang.String, java.lang.Object>
   * @author: zhangzx
   * @date: 2023/3/21 21:09
   * @version: 1.0.1
   * Modification History:
   * Date       Author       Version          Description
   * -----------------------------------------------------------
   * 2023/3/21  zhangzx       v1.0.1          init
   */
  @Override
  public Map<String, Object> saveShowUserApply(Map<String, Object> param)
  {
    ShowUserApplyPO showUserApplyPO = Map2ObjUtil.toObject(param, ShowUserApplyPO.class);
    //校验该手机号是否村子演示账号
    QueryWrapper<ShowUserApplyPO> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("phone", showUserApplyPO.getPhone());
    List<ShowUserApplyPO> editionRenewPOList = showUserApplyMapper.selectList(queryWrapper);
    if (!CollectionUtils.isEmpty(editionRenewPOList))
    {
      AssertMyUtil.errMsg("该手机号已注册演示账号已存在");
    }
    showUserApplyPO.setApplyStatus(Integer.parseInt(DicConstants.YSZHZT_01));
    showUserApplyPO.setStatus(Integer.parseInt(DicConstants.YXZT_01));
    showUserApplyPO.setCreateBy(ContextHolder.getUserAccount());
    showUserApplyPO.setCreateTime(LocalDateTime.now());
    showUserApplyPO.setLastUpdateBy(ContextHolder.getUserAccount());
    showUserApplyPO.setLastUpdateTime(LocalDateTime.now());
    showUserApplyMapper.save(showUserApplyPO);

    //插入轨迹信息
    this.insertShowUserApplyLog(showUserApplyPO, "新增");
    return transResultService.transResult(showUserApplyPO.toMaps(), this.getTransDic());
  }

  /**
   * @remark:修改演示账号信息
   * @param: id
   * @param: param
   * @return: java.util.Map<java.lang.String, java.lang.Object>
   * @author: zhangzx
   * @date: 2023/3/21 21:09
   * @version: 1.0.1
   * Modification History:
   * Date       Author       Version          Description
   * -----------------------------------------------------------
   * 2023/3/21  zhangzx       v1.0.1          init
   */
  @Override
  public Map<String, Object> updateShowUserApply(Long id, Map<String, Object> param)
  {
    AssertMyUtil.notNull(id, BizCode.METHOD_ARGS_NOTNULL, "id");
    ShowUserApplyPO showUserApplyPO = showUserApplyMapper.selectById(id);
    Map2ObjUtil.toObject(param, showUserApplyPO);
    if (showUserApplyPO.getApplyStatus() == Integer.parseInt(DicConstants.YSZHZT_01))
    {
      //校验该手机号是否村子演示账号
      QueryWrapper<ShowUserApplyPO> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("phone", showUserApplyPO.getPhone());
      queryWrapper.ne("id", id);
      List<ShowUserApplyPO> editionRenewPOList = showUserApplyMapper.selectList(queryWrapper);
      if (!CollectionUtils.isEmpty(editionRenewPOList))
      {
        AssertMyUtil.errMsg("该手机号已注册演示账号已存在");
      }
    }
    showUserApplyPO.setLastUpdateBy(ContextHolder.getUserAccount());
    showUserApplyPO.setLastUpdateTime(LocalDateTime.now());
    showUserApplyMapper.updateById(showUserApplyPO);

    //取出品牌信息
    String brandIdArr[] = showUserApplyPO.getBrandId().split(",");
    String brandNameArr[] = showUserApplyPO.getBrandName().split(",");
    //判断当前状态值，已提交的单据修改sys_company,sys_dept,app_user,cms_cloud_store表中数据
    if (showUserApplyPO.getApplyStatus() == Integer.parseInt(DicConstants.YSZHZT_02))
    {
      Map<String, Object> deptMap = this.saveOrUpdateDeptAndUser(showUserApplyPO, "修改");
      HashMap<String, Object> cloudStoreMap = new HashMap<>();
      cloudStoreMap.put("operateType", "修改");
      cloudStoreMap.put("storeDeptId", deptMap.get("deptId"));
      cloudStoreMap.put("companyId", deptMap.get("companyId"));
      cloudStoreMap.put("phone", showUserApplyPO.getPhone());
      cloudStoreMap.put("userName", showUserApplyPO.getUserName());
      cloudStoreMap.put("customerId", deptMap.get("customerId"));
      cloudStoreMap.put("customerDeptId", deptMap.get("customerDeptId"));
      cloudStoreMap.put("customerCode", deptMap.get("customerCode"));
      cloudStoreMap.put("customerName", deptMap.get("customerName"));
      cloudStoreMap.put("brandId", brandIdArr[0]);
      cloudStoreMap.put("brandName", brandNameArr[0]);
      cloudStoreMap.put("operator", showUserApplyPO.getLastUpdateBy());
      // 调用Feign接口修改门店信息
      Map<String, Object> cloudStoreFeignMap = cloudStoreFeignService.saveCloudStore(cloudStoreMap);
      JSONObject jsonCloudStore = JSONUtil.parseObj(cloudStoreFeignMap);
      String jsonStatus = jsonCloudStore.get("status").toString();
      if ("fail".equals(jsonStatus))
      {
        AssertMyUtil.errMsg(jsonCloudStore.get("message").toString());
      }
    }
    //插入轨迹信息
    this.insertShowUserApplyLog(showUserApplyPO, "修改");
    return transResultService.transResult(showUserApplyPO.toMaps(), this.getTransDic());
  }

  /**
   * @remark:演示账号提交方法
   * @param: id
   * @param: param
   * @return: java.util.Map<java.lang.String, java.lang.Object>
   * @author: zhangzx
   * @date: 2023/3/21 21:10
   * @version: 1.0.1
   * Modification History:
   * Date       Author       Version          Description
   * -----------------------------------------------------------
   * 2023/3/21  zhangzx       v1.0.1          init
   */
  @Override
  public Map<String, Object> updateSubmitShowUserApply(Long id, Map<String, Object> param)
  {
    AssertMyUtil.notNull(id, BizCode.METHOD_ARGS_NOTNULL, "id");
    ShowUserApplyPO showUserApplyPO = showUserApplyMapper.selectById(id);
    Map2ObjUtil.toObject(param, showUserApplyPO);

    showUserApplyPO.setApplyStatus(Integer.parseInt(DicConstants.YSZHZT_02));
    showUserApplyPO.setLastUpdateBy(ContextHolder.getUserAccount());
    showUserApplyPO.setLastUpdateTime(LocalDateTime.now());

    // 判断该账号在APP_USER表中是否存在
    Map<String, Object> checkAppUserMap = appUserMapper.findStoreAppUser(showUserApplyPO.getPhone());
    if (checkAppUserMap != null && checkAppUserMap.size() > 0)
    {
//      未认证的门店，已认证的门店，子账号的门店，进入公共资源库的门店
      // 判断当前账号是否存在dept_id
      if (StringUtils.isEmpty(checkAppUserMap.get("deptId")))
      {
        AssertMyUtil.errMsg("该手机号存在未认证的门店");
      }

      //判断账号类型，userKind == 102202
      if (!StringUtils.isEmpty(checkAppUserMap.get("userKind")) && DicConstants.APPYHLB_02.equals(checkAppUserMap.get("userKind")))
      {
        AssertMyUtil.errMsg("该手机号存在子账号的门店");
      }

      //调用Feign接口判断是否存在门店状态
      Map<String, Object> map = new HashMap<>();
      map.put("deptId", checkAppUserMap.get("deptId"));
      Map<String, Object> storeStatusMap = cloudStoreFeignService.findStoreStatus(map);
      JSONObject jsonStoreStatusMap = JSONUtil.parseObj(storeStatusMap);
      String jsonStatus = jsonStoreStatusMap.get("status").toString();
      if ("fail".equals(jsonStatus))
      {
        AssertMyUtil.errMsg(jsonStoreStatusMap.get("message").toString());
      }
      if (!StringUtils.isEmpty(jsonStoreStatusMap.get("datas")))
      {
        Map<String, Object> jsonMap = (Map<String, Object>) jsonStoreStatusMap.get("datas");
        String storeStatus = jsonMap.get("storeStatus").toString();
        String message = "";
        switch (storeStatus)
        {
          case "301401":
            message = "该手机号存在未认证的门店";
            break;
          case "301402":
            message = "该手机号存在认证中的门店";
            break;
          case "301403":
            message = "该手机号存在已认证的门店";
            break;
          case "301404":
            message = "该手机号存在已禁用的门店";
            break;
          case "301405":
            message = "该手机号存在进入公共资源库的门店";
            break;
        }
        AssertMyUtil.errMsg(message);
      }
    }

    //取出品牌信息
    String brandIdArr[] = showUserApplyPO.getBrandId().split(",");
    String brandNameArr[] = showUserApplyPO.getBrandName().split(",");
    Map<String, Object> deptMap = this.saveOrUpdateDeptAndUser(showUserApplyPO, "新增");
    HashMap<String, Object> cloudStoreMap = new HashMap<>();
    cloudStoreMap.put("operateType", "新增");
    cloudStoreMap.put("storeDeptId", deptMap.get("deptId"));
    cloudStoreMap.put("companyId", deptMap.get("companyId"));
    cloudStoreMap.put("phone", showUserApplyPO.getPhone());
    cloudStoreMap.put("userName", showUserApplyPO.getUserName());
    cloudStoreMap.put("customerId", deptMap.get("customerId"));
    cloudStoreMap.put("customerDeptId", deptMap.get("customerDeptId"));
    cloudStoreMap.put("customerCode", deptMap.get("customerCode"));
    cloudStoreMap.put("customerName", deptMap.get("customerName"));
    cloudStoreMap.put("brandId", brandIdArr[0]);
    cloudStoreMap.put("brandName", brandNameArr[0]);
    cloudStoreMap.put("operator", showUserApplyPO.getLastUpdateBy());
    // 调用Feign接口修改门店信息
    Map<String, Object> cloudStoreFeignMap = cloudStoreFeignService.saveCloudStore(cloudStoreMap);
    JSONObject jsonCloudStore = JSONUtil.parseObj(cloudStoreFeignMap);
    String jsonStatus = jsonCloudStore.get("status").toString();
    if ("fail".equals(jsonStatus))
    {
      AssertMyUtil.errMsg(jsonCloudStore.get("message").toString());
    }

    //回更deptId与companyId
    showUserApplyPO.setDeptId(Long.parseLong(deptMap.get("deptId").toString()));
    showUserApplyPO.setCompanyId(Long.parseLong(deptMap.get("companyId").toString()));
    showUserApplyPO.setAppUserId(Long.parseLong(deptMap.get("appUserId").toString()));
    showUserApplyMapper.updateById(showUserApplyPO);
    //插入轨迹信息
    this.insertShowUserApplyLog(showUserApplyPO, "提交");
    return transResultService.transResult(showUserApplyPO.toMaps(), this.getTransDic());
  }

  /**
   * @remark:新增或修改公司信息，部门信息，APP账号表
   * @param: showUserApplyPO
   * @param: type
   * @return: java.util.Map<java.lang.String, java.lang.Object>
   * @author: zhangzx
   * @date: 2023/3/21 21:10
   * @version: 1.0.1
   * Modification History:
   * Date       Author       Version          Description
   * -----------------------------------------------------------
   * 2023/3/21  zhangzx       v1.0.1          init
   */
  public Map<String, Object> saveOrUpdateDeptAndUser(ShowUserApplyPO showUserApplyPO, String type)
  {
    HashMap<String, Object> returnMap = new HashMap<>();
    //查询虚拟经销商
    Map<String, Object> inventedCustomerInfo = showUserApplyMapper.findInventedCustomer();
    if (inventedCustomerInfo == null || inventedCustomerInfo.size() == 0)
    {
      AssertMyUtil.errMsg("请先维护虚拟经销商信息");
    }
    if (type.equals("新增"))
    {
      //保存公司信息
      SysCompanyPO companyPO = new SysCompanyPO();
      companyPO.setCode("YSGS");
      companyPO.setCname("演示公司");
      companyPO.setSname("演示公司");
      companyPO.setContact(showUserApplyPO.getPhone());
      companyPO.setLegalPerson(showUserApplyPO.getUserName());
      companyPO.setType(Long.valueOf(DicConstant.GSLX_02));
      companyPO.setStatus(Integer.valueOf(DicConstant.YXBS_01));
      companyPO.setCreateBy(ContextHolder.getUserAccount());
      companyPO.setCreateTime(LocalDateTime.now());
      companyMapper.save(companyPO);
      returnMap.put("companyId", companyPO.getId());
      List<SysCompanyPO> companyPOList = new ArrayList<>();
      companyPOList.add(companyPO);
      redisCompanyFeignService.cacheCompanyById(companyPOList);

      //保存部门信息
      SysDeptPO deptPO = new SysDeptPO();
      deptPO.setDcode("YSBM");
      deptPO.setDname("演示部门");
      deptPO.setSname("演示部门");
      deptPO.setPid(Long.parseLong(inventedCustomerInfo.get("customerDeptId").toString()));
      deptPO.setLevel(Long.valueOf(DicConstant.JGJB_06));
      deptPO.setDeptType(Long.valueOf(DicConstant.ZZLB_14));
      deptPO.setBizStatus(Long.valueOf(DicConstant.ZZYWZT_01));
      deptPO.setStatus(Integer.valueOf(DicConstant.YXBS_01));
      deptPO.setCompanyId(companyPO.getId());
      deptPO.setCreateBy(ContextHolder.getUserAccount());
      deptPO.setCreateTime(LocalDateTime.now());
      deptMapper.save(deptPO);
      returnMap.put("deptId", deptPO.getId());
      redisDeptFeignService.updateDept(deptPO);

      //保存APP_USER数据
      AppUserPO appUserPO = new AppUserPO();
      appUserPO.setUserName(showUserApplyPO.getUserName());
      appUserPO.setPhone(showUserApplyPO.getPhone());
      appUserPO.setUserKind(Long.parseLong(DicConstants.APPYHLB_03));
      appUserPO.setCreateBy(ContextHolder.getUserAccount());
      appUserPO.setCreateTime(LocalDateTime.now());
      appUserPO.setDeptId(deptPO.getId());
      appUserPO.setCompanyId(deptPO.getCompanyId());
      appUserPO.setStatus(Integer.parseInt(DicConstant.YXBS_01));
      appUserPO.setBizType(DicConstants.APPYHYWLX_02);
      appUserMapper.save(appUserPO);
      returnMap.put("appUserId", appUserPO.getId());
    } else
    {
      //保存公司信息
      SysCompanyPO companyPO = companyMapper.selectById(showUserApplyPO.getCompanyId());
      companyPO.setContact(showUserApplyPO.getPhone());
      companyPO.setLegalPerson(showUserApplyPO.getUserName());
      companyPO.setLastUpdateBy(ContextHolder.getUserAccount());
      companyPO.setLastUpdateTime(LocalDateTime.now());
      companyMapper.updateById(companyPO);
      returnMap.put("companyId", companyPO.getId());
      List<SysCompanyPO> companyPOList = new ArrayList<>();
      companyPOList.add(companyPO);
      redisCompanyFeignService.cacheCompanyById(companyPOList);

      //保存部门信息
      SysDeptPO deptPO = deptMapper.selectById(showUserApplyPO.getDeptId());
      deptPO.setLastUpdateBy(ContextHolder.getUserAccount());
      deptPO.setLastUpdateTime(LocalDateTime.now());
      deptMapper.updateById(deptPO);
      returnMap.put("deptId", deptPO.getId());
      redisDeptFeignService.updateDept(deptPO);

      //保存APP_USER数据
      AppUserPO appUserPO = appUserMapper.selectById(showUserApplyPO.getAppUserId());
      appUserPO.setUserName(showUserApplyPO.getUserName());
      appUserPO.setPhone(showUserApplyPO.getPhone());
      appUserPO.setLastUpdateBy(ContextHolder.getUserAccount());
      appUserPO.setLastUpdateTime(LocalDateTime.now());
      appUserMapper.updateById(appUserPO);
      returnMap.put("appUserId", appUserPO.getId());
    }
    returnMap.put("customerId", inventedCustomerInfo.get("customerId"));
    returnMap.put("customerDeptId", inventedCustomerInfo.get("customerDeptId"));
    returnMap.put("customerCode", inventedCustomerInfo.get("customerCode"));
    returnMap.put("customerName", inventedCustomerInfo.get("customerName"));
    return returnMap;
  }

  /**
   * @remark:插入演示账号日志信息
   * @param: showUserApplyPO
   * @param: type
   * @return: void
   * @author: zhangzx
   * @date: 2023/3/21 21:11
   * @version: 1.0.1
   * Modification History:
   * Date       Author       Version          Description
   * -----------------------------------------------------------
   * 2023/3/21  zhangzx       v1.0.1          init
   */
  public void insertShowUserApplyLog(ShowUserApplyPO showUserApplyPO, String type)
  {
    ShowUserApplyLogPO showUserApplyLogPO = new ShowUserApplyLogPO();
    showUserApplyLogPO.setApplyId(showUserApplyPO.getId());
    showUserApplyLogPO.setOperate(type);
    showUserApplyLogPO.setStatus(Integer.parseInt(DicConstants.YXZT_01));
    showUserApplyLogPO.setCreateBy(ContextHolder.getUserAccount());
    showUserApplyLogPO.setCreateTime(LocalDateTime.now());
    showUserApplyLogPO.setLastUpdateBy(ContextHolder.getUserAccount());
    showUserApplyLogPO.setLastUpdateTime(LocalDateTime.now());
    showUserApplyLogMapper.save(showUserApplyLogPO);
  }

  /**
   * @remark:字典翻译方法
   * @param:
   * @return: java.util.HashMap<java.lang.String, java.lang.String>
   * @author: zhangzx
   * @date: 2023/3/21 21:11
   * @version: 1.0.1
   * Modification History:
   * Date       Author       Version          Description
   * -----------------------------------------------------------
   * 2023/3/21  zhangzx       v1.0.1          init
   */
  public HashMap<String, String> getTransDic()
  {
    HashMap<String, String> transHash = new HashMap<>();
    transHash.put("applyStatus", "dic|" + DicConstants.YSZHZT);
    transHash.put("status", "dic|" + DicConstants.YXZT);
    transHash.put("deptId", "dept|o");
    transHash.put("createBy", "user|o");
    transHash.put("lastUpdateBy", "user|o");
    transHash.put("createTime", "date|" + FormatConstant.SIMPLE_DATE_TIME_FORMAT);
    transHash.put("lastUpdateTime", "date|" + FormatConstant.SIMPLE_DATE_TIME_FORMAT);
    return transHash;
  }
}
